package com.study.java8;

import java.util.Optional;

/**
 * @author ysy
 * @version 1.0
 * @Title: OptionalTest
 * @Note <b>ProjectName:</b> cusc-venus
 * <br><b>PackageName:</b> com.cusc.venus.acc.center.util
 * <br><b>ClassName:</b>
 * <br><b>Date:</b>
 *
 */
public class OptionalTest {

    /**
     * 1. Optional 是用来作为方法返回值的 【尽量不要在其他场景下使用该对象】
     * 2. Optional 是为了清晰地表达返回值中没有结果的可能性
     * 3. 且如果直接返回 null 很可能导致调用端产生错误（尤其是NullPointerException）
     *
     * Optional is intended to provide a limited mechanism for library method return types
     * where there needed to be a clear way to represent “no result," and using null for such was overwhelmingly likely to cause errors
     **/
    // 空值处理：避免显式的null检查
    public static void main(String[] args) {
        Optional< String > fullName = Optional.ofNullable( null );
        System.out.println( "Full Name is set? " + fullName.isPresent() );
        System.out.println( "Full Name: " + fullName.orElseGet( () -> "[none]" ) );
        System.out.println( fullName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) );

        Optional< String > firstName = Optional.of( "Tom" );
        System.out.println( "First Name is set? " + firstName.isPresent() );
        System.out.println( "First Name: " + firstName.orElseGet( () -> "[none]" ) );
        System.out.println( firstName.map( s -> "Hey " + s + "!" ).orElse( "Hey Stranger!" ) );
        System.out.println();

        Integer value1 = null;
        Integer value2 = new Integer(10);
        // Optional.ofNullable - 允许传递为 null 参数
        Optional<Integer> a = Optional.ofNullable(value1);
        // Optional.of - 如果传递的参数是 null，抛出异常 NullPointerException
        Optional<Integer> b = Optional.of(value2);
        System.out.println(OptionalTest.sum(a,b));
    }

    public static Integer sum(Optional<Integer> a, Optional<Integer> b){
        // Optional.isPresent - 判断值是否存在
        System.out.println("第一个参数值存在: " + a.isPresent());
        System.out.println("第二个参数值存在: " + b.isPresent());

        // Optional.orElse - 如果值存在，返回它，否则返回默认值
        Integer value1 = a.orElse(new Integer(0));

        //Optional.get - 获取值，值需要存在
        Integer value2 = b.get();
        return value1 + value2;
    }
}
